﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;
using HHG.Common;

namespace OnLineExam.Web.mag.Handler
{
	/// <summary>
	/// JudgeHandler 的摘要说明
	/// </summary>
	public class JudgeHandler : IHttpHandler
	{
		private HttpContext _httpContext;
		private HttpRequest _httpRequest;
		private HttpResponse _httpResponse;
		private Data.OnlineExamEntities _dbContext;
		private Data.EfRepository<OnLineExam.Data.JudgeProblem> _JudgeRepository;

		public void ProcessRequest(HttpContext context)
		{
			_httpContext = context;
			_httpRequest = context.Request;
			_httpResponse = context.Response;
			_dbContext = new Data.OnlineExamEntities();
			_dbContext.Configuration.LazyLoadingEnabled = false;
			_JudgeRepository = new Data.EfRepository<OnLineExam.Data.JudgeProblem>(_dbContext);


			context.Response.ContentType = "text/plain";


			string type = context.Request.Params["type"];

			var id = context.Request.QueryString["ID"].GetInt();


			switch (type)
			{
				case "getlist":
					GetList();
					break;

				case "edit":
					#region 根据ID获取信息

					var entity = _JudgeRepository.GetById(id);

					WriteJson(entity);

					#endregion
					break;
				case "addsave":
					#region 提交修改
					AddSave();


					#endregion
					break;
				case "editsave":
					EditSave();
					break;
				case "del":
					#region 删除
					var deleteId = _httpRequest.Form["ID"].GetInt();
					_JudgeRepository.Delete(_JudgeRepository.GetById(deleteId));
					WriteJson(1);
					#endregion
					break;
				default:
					break;
			}

		}
		private void EditSave()
		{
			var id = _httpRequest.Form["hdID"].GetInt();
			var entity = _JudgeRepository.GetById(id); ;


			entity.PaperID = int.Parse(_httpRequest.Params["selectPaper"]);
			entity.Title = _httpRequest.Params["txtTitle"];
			var d1 = _httpRequest.Params["rdAnswer"];

			entity.Answer = bool.Parse(d1);

			_JudgeRepository.Update(entity);
			WriteJson(id);
		}
		private void AddSave()
		{
			var entity = new OnLineExam.Data.JudgeProblem();


			entity.PaperID = int.Parse(_httpRequest.Params["selectPaper"]);
			entity.Title = _httpRequest.Params["txtTitle"];
			var d1 = _httpRequest.Params["rdAnswer"];

			entity.Answer = bool.Parse(d1);

			_JudgeRepository.Insert(entity);
			WriteJson(1);
		}
		private void GetList()
		{
			var id = _httpRequest.Params["id"].GetInt();// 试卷id
			int page = _httpRequest.Params["page"].GetInt();
			int rows = _httpRequest.Params["rows"].GetInt();


			var query = _JudgeRepository.TableNoTracking;
			if (id > 0)
			{
				query = query.Where(s => s.PaperID == id);
			}
			var result = EasyuiDataGrid.Create(query.Count(), query.OrderBy(s => s.ID).Skip((page - 1) * rows).Take(rows).ToList());

			WriteJson(result);
		}

		private void WriteJson(object data)
		{
			_httpResponse.Write(data.SerializeObject());
			_httpResponse.End();
		}

		public bool IsReusable
		{
			get
			{
				return false;
			}
		}
	}
}